/**
 * Created by Administrator on 2017/6/12.
 */
var express = require('express');
var config = require('./config.json');
var passport = require('./app/util/passport');
var bodyParser = require('body-parser');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var mongoStore = require('connect-mongo')(session);
var log4js = require('./app/util/log');
var initDB = require('./app/db/initDB');
var port = config.port;

//路由
var indexRouter = require('./app/router/index');
var movieRouter = require('./app/router/movie');
var userRouter = require('./app/router/user');
var commentRouter = require('./app/router/comment');
var categoryRouter = require('./app/router/category');
var thirdAuthRouter = require('./app/router/thirdAuth');

var app = express();
log4js.use(app);

//设置view engine
app.locals.pretty = true;
app.set('views', './views/pages');
app.set('view engine', 'jade');
app.use(express.static('public'));

//对post请求的请求体进行解析
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

//使用cookie
app.use(cookieParser());

//使用session
app.use(session({
  secret: config.session.secret,
  name: config.session.name,
  // cookie: {maxAge: config.session.cookie.maxAge},
  resave: config.session.resave,
  saveUninitialized: config.session.saveUninitialized,
  store: new mongoStore({   //创建新的mongodb数据库
    url: config.dbUrl
  })
}));

//第三方认证
app.use(passport.initialize());
app.use(passport.session());

//没有挂载路径的中间件，通过该路由的每个请求都会执行该中间件
app.use(function (req, res, next) {
  res.locals.user = req.session.user;
  next();
});

//设置路由
app.use('/', indexRouter);
app.use('/movie', movieRouter);
app.use('/user', userRouter);
app.use('/comment', commentRouter);
app.use('/category', categoryRouter);
app.use('/auth', thirdAuthRouter);

//初始化数据库
initDB.init();

//处理错误的中间件
app.use(function (err, req, res, next) {
  log4js.logger('errLog').error(err);
  res.render('common/500');
  next();
});

var server = app.listen(port, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('movie web app listening at http://%s:%s', host, port);
});

module.exports = app;